//
//  CZEmoticonInputView.swift
//  微博表情键盘
//
//  Created by Summer on 2017/12/22.
//  Copyright © 2017年 Summer. All rights reserved.
//

import UIKit

private let cellId = "cellId"

class CZEmoticonInputView: UIView {

    @IBOutlet weak var collectionView: UICollectionView!
    
    @IBOutlet weak var toolBar: UIView!
    
    private var emoticonSelectedCallBack: ((_ em: CZEmoticon?)->())?
    
    class func emoticonInputView(emoticonSelected: @escaping (_ em: CZEmoticon?)->()) -> CZEmoticonInputView {
        
        let nib = UINib(nibName: "CZEmoticonInputView", bundle: nil)
        let view = nib.instantiate(withOwner: nil, options: nil)[0] as! CZEmoticonInputView
        
        // 记录闭包，类方法中
        view.emoticonSelectedCallBack = emoticonSelected
        
        return view
    }

    override func awakeFromNib() {
//        let nib = UINib(nibName: "CZEmoticonCell", bundle: nil)
//        collectionView.register(nib, forCellWithReuseIdentifier: cellId)
        collectionView.register(CZEmoticonCell.self, forCellWithReuseIdentifier: cellId)
    }
    
}

extension CZEmoticonInputView: UICollectionViewDataSource {
    
    // 分组数量 - 返回表情包的数量
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return CZEmoticonManager.shared.packages.count
    }
    
    // 返回每个分组中的表情‘页’的数量
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return CZEmoticonManager.shared.packages[section].numberOfPages
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! CZEmoticonCell
        
        cell.emoticons = CZEmoticonManager.shared.packages[indexPath.section].emoticon(page: indexPath.row)
        
        cell.delegate = self
        
        return cell
    }
    
}

extension CZEmoticonInputView: CZEmoticonCellDelegate {
    func emoticonSelected(em: CZEmoticon?) {
        
        // 执行闭包
        emoticonSelectedCallBack?(em)
    }
}
